package rs.etf.kdp.server;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import rs.etf.kdp.client.Connections;
import rs.etf.kdp.client.Job;

/**
 * @author Djordje Vukovic
 * @version 1.0
 * @created 20-May-2011 2:30:22 AM
 */
public class SimpleJobDivider implements JobDivider {

	public SimpleJobDivider(){

	}


	/**
	 * 
	 * @param parts
	 * @param jobToDivide
	 */
	public List<Part> divideJob(int numberOfEqualParts, Job jobToDivide){
		
		List<Part> parts = new ArrayList<Part>();
		for(int i=0; i<numberOfEqualParts; i++)
		{
			parts.add(new Part(jobToDivide.getServerID(), jobToDivide.getIdentifier(), jobToDivide.getTypeOfSimulation(), jobToDivide.getLogicTime()));
		}
		
		//Create Hash map
		
		HashMap<Long, List<TokenizedConnection>> builder = new HashMap<Long, List<TokenizedConnection>>(); //Long - component id String - list of connections
		
		Connections ctions = jobToDivide.getConnections();
		List<String[]> cnn = null;
		
		if(ctions!=null)
		{
			cnn = ctions.getListOfConnections();
		}
		
		// put connections in hash table
		for(String[] s : cnn)
		{
			long id = Long.parseLong(s[0]);
			TokenizedConnection tc = new TokenizedConnection(Long.parseLong(s[0]),Long.parseLong(s[1]),Long.parseLong(s[2]),Long.parseLong(s[3]));
			List<TokenizedConnection> inTable = builder.get(id);
			if(inTable == null)
			{
				inTable = new ArrayList<TokenizedConnection>();
				builder.put(id, inTable);
			}
			inTable.add(tc);
		}
		
		//divide components
		List<String> comp = jobToDivide.getComponents().getListOfComponents();
		int numberOfComponents = comp.size();
		int sizeOfPartition = numberOfComponents / numberOfEqualParts;
		
		int currentComponent = 0;
		int currentPart = 0;
		int cnt = 0;

		while(cnt<numberOfComponents)
		{
			//parts.get(currentPart).addComponent(comp.get(currentComponent));
			parts.get(currentPart).addComponent(comp.get(cnt));
			currentComponent++;
			cnt++;
			if(currentComponent == sizeOfPartition)
			{
				if(currentPart + 1 < numberOfEqualParts)
				{
					currentPart++;
					currentComponent = 0;
				}
			}
		} 
		
		// divide connections
		
		for(Part p : parts)
		{
			List<String> component = p.getComponents();
			for(String s : component)
			{
				int indexOfSpace = s.indexOf(' ');
				String sid = s.substring(0, indexOfSpace); 
				long id = 0;
				try
				{
					id = Long.parseLong(sid);
				} catch(NumberFormatException nfe)
				{
					System.out.println("Error while converting " + sid + " to long");
					return null;
				}
				
				List<TokenizedConnection> fromBuilder = builder.get(id);
				if(fromBuilder!=null)
				{
					p.addListOfConnections(fromBuilder);
				}
			}
		}
		
		return parts;
	}

}